import React, { Component } from 'react';
import { connect } from 'dva';
import { formatMessage, FormattedMessage } from 'umi/locale';
import Link from 'umi/link';
import { Checkbox, Alert, Icon } from 'antd';
import Login from '@/components/Login';
import styles from './Login.less';
import { LoginConfig } from '../../utils/constant';

const { Tab, UserName, Password, Mobile, Captcha, Submit } = Login;

@connect(({ login, loading }) => ({
  login,
  submitting: loading.effects['login/login'],
}))
class LoginPage extends Component {
  state = {
    type: LoginConfig.enableAccountLogin ? 'account' : (LoginConfig.enableTelephoneLogin ? 'mobile' : 'account'),
    autoLogin: true,
  };

  onTabChange = type => {
    this.setState({ type });
  };

  onGetCaptcha = () =>
    new Promise((resolve, reject) => {
      this.loginForm.validateFields(['mobile'], {}, (err, values) => {
        if (err) {
          reject(err);
        } else {
          const { dispatch } = this.props;
          dispatch({
            type: 'login/getCaptcha',
            payload: values.mobile,
          })
            .then(resolve)
            .catch(reject);
        }
      });
    });

  handleSubmit = (err, values) => {
    const { type } = this.state;
    if (!err) {
      const { dispatch } = this.props;
      dispatch({
        type: 'login/login',
        payload: {
          ...values,
          type,
        },
      });
    }
  };

  changeAutoLogin = e => {
    this.setState({
      autoLogin: e.target.checked,
    });
  };

  renderMessage = content => (
    <Alert style={{ marginBottom: 24 }} message={content} type="error" showIcon />
  );

  render() {
    const { login, submitting } = this.props;
    const { type, autoLogin } = this.state;
    return (
      <div className={styles.main}>
        <Login
          defaultActiveKey={type}
          onTabChange={this.onTabChange}
          onSubmit={this.handleSubmit}
          ref={form => {
            this.loginForm = form;
          }}
        >
          {LoginConfig.enableAccountLogin ? (
            <Tab key="account" tab={formatMessage({ id: 'app.login.tab-login-credentials' })}>
              {
                login.status === 'error' &&
                login.type === 'account' &&
                !submitting &&
                this.renderMessage(formatMessage({ id: 'app.login.message-invalid-credentials' }))
              }
              <UserName
                name="userName"
                placeholder={formatMessage({ id: 'app.login.form.userName.placeholder' })}
                rules={[{ required: true, whitespace: true, message: formatMessage({ id: 'app.login.form.userName.rules' }) }]}
              />
              <Password
                name="password"
                placeholder={formatMessage({ id: 'app.login.form.password.placeholder' })}
                onPressEnter={() => this.loginForm.validateFields(this.handleSubmit)}
                rules={[{ required: true, message: formatMessage({ id: 'app.login.form.password.rules' }) }]}
              />
            </Tab>
          ) : ''}
          {LoginConfig.enableTelephoneLogin ? (
            <Tab key="mobile" tab={formatMessage({ id: 'app.login.tab-login-mobile' })}>
              {
                login.status === 'error' &&
                login.type === 'mobile' &&
                !submitting &&
                this.renderMessage(formatMessage({ id: 'app.login.message-invalid-verification-code' }))
              }
              <Mobile
                name="mobile"
                placeholder={formatMessage({ id: 'app.login.form.mobile.placeholder' })}
                rules={[{ required: true, whitespace: true, message: formatMessage({ id: 'app.login.form.mobile.rules' }) }]}
              />
              <Captcha
                name="captcha"
                placeholder={formatMessage({ id: 'app.login.form.captcha.placeholder' })}
                rules={[{ required: true, whitespace: true, message: formatMessage({ id: 'app.login.form.captcha.rules' }) }]}
                countDown={120}
                onGetCaptcha={this.onGetCaptcha}
              />
            </Tab>
          ) : ''}
          <div>
            <Checkbox checked={autoLogin} onChange={this.changeAutoLogin}>
              <FormattedMessage id="app.login.remember-me" />
            </Checkbox>
            {LoginConfig.enableForgotPassword ? (
              <a style={{ float: 'right' }} href="">
                <FormattedMessage id="app.login.forgot-password" />
              </a>
            ) : ''}
          </div>
          <Submit loading={submitting}>
            <FormattedMessage id="app.login.login" />
          </Submit>
          <div className={styles.other}>
            {LoginConfig.enableAuth2Login ? (
              <React.Fragment>
                <FormattedMessage id="app.login.sign-in-with" />
                <Icon type="alipay-circle" className={styles.icon} theme="outlined" />
                <Icon type="taobao-circle" className={styles.icon} theme="outlined" />
                <Icon type="weibo-circle" className={styles.icon} theme="outlined" />
              </React.Fragment>
            ) : ''}
            {LoginConfig.enableRegistered ? (
              <Link className={styles.register} to="/user/register">
                <FormattedMessage id="app.login.signup" />
              </Link>
            ) : ''}
          </div>
        </Login>
      </div>
    );
  }
}

export default LoginPage;
